package com.webtair.session;

import com.webtair.session.artifact.SessionInfo;
import com.webtair.session.config.BadConfigException;
import com.webtair.session.config.ConfigBean;
import com.webtair.session.security.SecurityException;
import com.webtair.session.security.SessionSecurity;
import com.webtair.session.user.UserInfo;

public class SessionsFacade {
	private static SessionsFacade instance;

	private static boolean configured = false;
	
	private static ConfigBean configBean;
	
	// private non-static members
	private SessionMan sessions;
	
	private SessionSecurity security;
	
	private Class sessionClass;
	
	private SessionsFacade(){
		this.sessionClass = configBean.getSessionsInfoClass();
	//	if(cl.isAssignableFrom(SessionInfo.class)){
	//		sessions = new SessionMan();
	//	}
		sessions = new SessionMan();
		
		Class securityClass = configBean.getSecurityClass();
		try {
			security = (SessionSecurity)securityClass.newInstance();
		} catch (InstantiationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public static synchronized SessionsFacade getInstance(){
		if(instance == null){
			if(!configured) {
				try {
					configure(new ConfigBean());
				} catch (BadConfigException e) {
					// impossible
				}
			}
			instance = new SessionsFacade();
		}
		return instance;
	}
	
	public void login(UserInfo userInfo) throws SecurityException {
		boolean valid = security.validateUser(userInfo);
		if(!valid)
			throw new SecurityException("Invalid username/password");
		SessionInfo info = null;
		try {
			info = (SessionInfo) sessionClass.newInstance();
		} catch (InstantiationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		sessions.putSessionInfo(userInfo.getLogin(),info);
	}

	public static void configure(ConfigBean bean) throws BadConfigException{
		if(configured)
			throw new BadConfigException("Already configured");
		configBean = bean;
		configured = true;
	}
}
